package com.sinosoft.cloud.access.transformer;

import com.sinosoft.cloud.access.entity.TranData;
import com.xiaoleilu.hutool.util.BeanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.io.IOException;
import java.util.*;

import static com.sinosoft.cloud.access.AccessConfiguration.BASE_PACKAGE;


/**
 * cloud-access
 *
 * @title: cloud-access
 * @package: com.sinosoft.cloud.access.transformer
 * @author: yangming
 * @date: 2017/11/15 下午6:45
 */
public class Validation {
    private static ExpressionParser parser = new SpelExpressionParser();
    List<ValidationItem> validationItems = new LinkedList<>();
    List<String> errors = new LinkedList<>();

    private static final String VALIDATION_FILE = "/validation.properties";

    private Hashtable<String, ValidationItem> keyHashMap = new Hashtable<>();
    private HashMap<String, Expression> expressionHashMap = new HashMap<>();


    public Validation(String accessName) {
        Resource resource = new ClassPathResource(BASE_PACKAGE + accessName + VALIDATION_FILE);
        Properties properties = null;
        try {
            if (!resource.exists()) {
                return;
            }
            properties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (properties != null) {

            Enumeration em = properties.propertyNames();

//            ValidationItem validationItem = new ValidationItem();
            while (em.hasMoreElements()) {
                String key = (String) em.nextElement();

                String[] keys = key.split("\\.");
                int index = keys.length - 2;

                ValidationItem validationItem = new ValidationItem();
                if (null == keyHashMap.get(keys[index])) {
                    if (key.endsWith("check")) {
                        validationItem.setRule(properties.getProperty(key));
                    }
                    if (key.endsWith("message")) {
                        validationItem.setMsg(properties.getProperty(key));
                    }
                    keyHashMap.put(keys[index], validationItem);
                    continue;
                }

                validationItem = keyHashMap.get(keys[index]);
                if (key.endsWith("check")) {
                    validationItem.setRule(properties.getProperty(key));
                }
                if (key.endsWith("message")) {
                    validationItem.setMsg(properties.getProperty(key));
                }
                if (validationItem != null && validationItem.getMsg() != null && validationItem.getRule() != null) {
                    validationItems.add(validationItem);
                    keyHashMap.remove(keys[index]);
                }
            }
        }
    }

    public boolean check(TranData data) {
        Map map = BeanUtil.beanToMap(data, false, true);
        StandardEvaluationContext headContext = new StandardEvaluationContext();
        headContext.setVariables(map);
        for (ValidationItem item : validationItems) {
            Expression expression = expressionHashMap.get(item.getRule());
            if (expression == null) {
                expression = parser.parseExpression(item.getRule());
                expressionHashMap.put(item.getRule(), expression);
            }
            boolean result = expression.getValue(headContext, Boolean.class);
            if (result) {
                errors.add(item.getMsg());
            }
        }
        if (errors.size() > 0) {
            return false;
        }
        return true;
    }

    public List<String> getErrors() {
        return errors;
    }

    public void setErrors(List<String> errors) {
        this.errors = errors;
    }

    public static void main(String[] args) throws IOException {
    }
}
